package rowan.application.quickaccess.tabs;

import java.util.HashMap;
import rowan.application.quickaccess.*;
import rowan.application.quickaccess.rss.RssDisplayItem;
import rowan.application.quickaccess.rss.RssDbHelper;
import rowan.application.quickaccess.rss.RssPreferences;
import rowan.application.quickaccess.rss.parser.ParsedDataSet;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
//import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/* 			 RSS TAB		
 * 			
 * Displays different types of RSS Feeds
 * 
 * 	Each feed has a Feed ID, every feed ID is detailed in the RssDbHelper
 *  
 *  @author Tom
 */
public class RSSDisplay extends Activity implements OnClickListener, OnItemSelectedListener{
	
	
	private TextView[] titles;
	private TextView[] descriptions;
	private ParsedDataSet parsedDataSet;
	private HashMap<View,RssDisplayItem> rssDisplayItems = new HashMap<View, RssDisplayItem>();
	private ImageView[] images;
	private LinearLayout layout = null;
	private ProgressDialog progressDialog;
	
	public static final int ROWAN_FEED = 0;
	public static final int TWITTER_FEED = 1;
	public static final int SPORTS_FEED = 2;
	public static final int REFRESH_ID = Menu.FIRST;
	public static final int PREFS_ID = Menu.FIRST+1;
	
	private int feedID; 
	private RssDbHelper mDbHelper;
	
	
    /** 
     * Has a given Url, creates an XML reader and attempts to parse the URL with RowanRSSHandler
     * 
     *	If Successful the method displayData() is called, and creates all titles 
     *		and descriptions from the parsedDataSet
     *
     *	If we get an error a TextView is setup and displayed with information
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rss); 
        mDbHelper = new RssDbHelper(this);
        mDbHelper.open();
        
//        getPreferences(mode)
        
      
      Spinner spinner = (Spinner)findViewById(R.id.feeds);
      spinner.setOnItemSelectedListener(this);
       feedID = ROWAN_FEED;

       
       UpdateThread ut = new UpdateThread();
       // Take data set, fill in database!
       if (mDbHelper.getDatabase(feedID) == null)
    	   ut.start();
       else{
    	   parsedDataSet = mDbHelper.getDatabase(feedID);
       
    	   displayData();
       }
       
       mDbHelper.close();
    }
    
    /**
     * When application Starts (is called after onCreate() or onRestart() )
     * 
     * Here we are going to extract the last updated rss feed Date and compare it to right now
     * 
     * @param savedInstanceState
     */
    public void onStart(Bundle savedInstanceState)
    {
    	// TODO measure dates and stuff
    }
    
    /**
     * Takes the layout from the XML file used to create this activities view
     * 
     * Creates Titles and Descriptions and plugs them into the layout
     */
    public void displayData()
    {
    	if (layout == null)
    		layout = (LinearLayout)findViewById(R.id.layout);
    	
    	layout.removeAllViews();
    	// SETS HOW MANY TITLES THERE WILL BE
    	int si = parsedDataSet.getTitles().size();
    	titles = new TextView[si];
    	descriptions = new TextView[titles.length];
    	images = new ImageView[titles.length-1];
    	
    	
    	
    	int i = 0;
    		for (TextView title : titles)
    		{
    			RssDisplayItem rssItem = new RssDisplayItem(parsedDataSet.getTitles().get(i), parsedDataSet.getDescs().get(i), parsedDataSet.getLinks().get(i));
    			
    			// First lets create the Views for each new piece of information
    			title = new TextView(this);
    			descriptions[i] = new TextView(this);
    			
    			///////////
    			title.setText(parsedDataSet.getTitles().get(i));
    			title.setOnClickListener(this);
    			title.setTextAppearance(this, R.style.TitleStyle);
    			title.setBackgroundColor(Color.parseColor("#ffebad"));
    			title.setPadding(0,0,0,0);
    			
    			///////////
    			
    	    	/////////////
    			// setup the description for  the title
    			
    			String text = parsedDataSet.getDescs().get(i).replaceAll("<img src.*/>", "");
    			text = text.replaceAll("&ndash;" , "-");
    			text = text.replace("&rsquo;", "'");
    			descriptions[i].setText(text);
    			descriptions[i].setPadding(0, 0, 0, 20);
    			descriptions[i].setTextColor(Color.parseColor("#000000"));
    			
    			if (i>0 && feedID == TWITTER_FEED)
    			{
    				title.setText("RowanUniversity:");
    				text = text.replaceAll("RowanUniversity:", "");
    				descriptions[i].setText(text);
    				Linkify.addLinks(descriptions[i], Linkify.ALL);
    			}
    			
    			
    			// Formating for the Sports feed
    			if (i>0 && feedID == SPORTS_FEED){
        			images[i-1] = new ImageView(this);
        			images[i-1].setPadding(0, 0, 0, 0);
//        			BitmapFactory bf = new BitmapFactory();
        			BitmapFactory.Options ad = new BitmapFactory.Options();
        			ad.inSampleSize = 4; 
//        			images[i-1].setImageBitmap(bf.decodeByteArray(parsedDataSet.getImgs().get(i-1), 0, parsedDataSet.getImgs().get(i-1).length));
        			images[i-1].setAdjustViewBounds(true);
        			images[i-1].setMaxHeight(260);
//        			title.set
        			title.setBackgroundColor(Color.parseColor("#340d03"));
        			title.setTextColor(Color.parseColor("#FFE8AB"));
        			title.setGravity(Gravity.CENTER);

        	    	layout.addView(images[i-1]);
        	    	rssDisplayItems.put(images[i-1], rssItem);
        		}
    			// We want to add views last, so we can get the order right
    			layout.addView(title);
    			layout.addView(descriptions[i]);
    			
    			
    			///////////// adding to hashmap
    			rssDisplayItems.put(title, rssItem);
    			rssDisplayItems.put(descriptions[i], rssItem);
    			
    			
    			i++;
    		}
    	if (i==1)
    	{
    		TextView text = new TextView(this);
    		text.setText("No Current Headlines");
    		text.setPadding(0, 20, 0, 0);
    		text.setTextColor(Color.parseColor("#656565"));
    		text.setGravity(Gravity.CENTER_HORIZONTAL);
    		layout.addView(text);
    	}
    }

    /**
     * Uses the titles (which are TextViews with THIS action listener) and opens the correct link
     * associated with that TextView
     * 
     * This method checks which TextView reference was clicked and gives the correct link
     * 
     * @param v The View clicked
     */
	@Override
	public void onClick(View v) {
//		TextView tv = (TextView)v;
//		for (int i=0; i<parsedDataSet.getTitles().size(); i++)
//		{
//			if (tv.getText() == parsedDataSet.getTitles().get(i))
//			{
//				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(parsedDataSet.getLinks().get(i)));
//                startActivity(intent);
//			}
//		}
		RssDisplayItem rssItem = rssDisplayItems.get(v);
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(rssItem.getLink()));
		startActivity(intent);
	}

	
	/**
	 * Loads the selected RssFeed
	 *  If the feed is not yet created, the feed will be parsed and created
	 *  otherwise it will always get the information from the database
	 */
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		
		String a = parent.getItemAtPosition(pos).toString();
		if ((a.equalsIgnoreCase("rowan") && feedID != ROWAN_FEED)
					|| a.equalsIgnoreCase("twitter") && feedID != TWITTER_FEED
					|| a.equalsIgnoreCase("sports") && feedID != SPORTS_FEED){
			if (a.equalsIgnoreCase("twitter")){
				feedID = TWITTER_FEED;
			}
			else if (a.equalsIgnoreCase("rowan")) {
				feedID = ROWAN_FEED;
			}
			else if (a.equalsIgnoreCase("sports")) {
				feedID = SPORTS_FEED;
			}
		mDbHelper.open();
		// we are going to find what feed we are working with

				if (mDbHelper.getDatabase(feedID) != null)
				{
					
					Log.i(this.toString(), "We did not parse anything and have the data");
				}
				else{
					mDbHelper.fillDataBase(feedID);
				}
		parsedDataSet = mDbHelper.getDatabase(feedID);			
		mDbHelper.close();
		displayData();
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// nothing to do
		
	}
	// ----------------------------------------------------
	
	/**
	 * Creates all menu items
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, REFRESH_ID, 0, "Refresh");
        menu.add(Menu.NONE, PREFS_ID, 1, "Preferences");
        return result;
    }

    
    /**
     * Refreshes the current feed 
     * 
     * Gets a new dataSet from the database and displays the data
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	UpdateThread ut = new UpdateThread();
//    	ut.setDaemon(false);
    	switch (item.getItemId()) {
        case REFRESH_ID:
        	progressDialog = new ProgressDialog(this);
        	progressDialog.setTitle("Loading");
        	progressDialog.setMessage("Please wait...");
        	progressDialog.show();
        	ut.start();
            return true;
            
        case PREFS_ID:
        	startActivity(new Intent(this, RssPreferences.class));
        	return true;
        }
        return super.onOptionsItemSelected(item);
    }
	 
    // Displays how many new items were added to the feed with a toast
    public void toastRefreshItems()
    {
    	Toast.makeText(this, parsedDataSet.getNumOfNewItems() +" New Item(s)", Toast.LENGTH_SHORT).show();
    }
    
    // Custom handler to update display when recieving a message
    private Handler uiUpdate = new Handler() {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		if (progressDialog != null){ // first time rss feeder is being run
    			progressDialog.dismiss();
    			toastRefreshItems();
    		}
    		displayData();
    	}
    };
    
    /**
     * This is the updateThread which runs mDbHelper fillDataBase(feedID) which updates the feed selected
     * 
     * A message is then sent to a Handler (uiUpdate) to update the display because this thread
     * 		can't touch RSSDisplay's views
     * 
     * @author Tom
     */
    class UpdateThread extends Thread
	{
		@Override
		public void run() {
			super.run();
			mDbHelper.open();
			parsedDataSet =mDbHelper.fillDataBase(feedID);
			uiUpdate.sendMessage(uiUpdate.obtainMessage());
			mDbHelper.close();
		}	
	}
 
}

